package auth

import (
	"FYKJ_Admin/models/auth"
	"FYKJ_Admin/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"math"
	"strings"
	"time"
)

type RoleController struct {
	beego.Controller
}

//角色列表
func (a *RoleController) List() {
	o := orm.NewOrm()
	qs := o.QueryTable("sys_role").Filter("is_delete", 0)
	roles := []auth.Role{}
	//每页显示条数
	pagePerNum :=8
	//当前页
	currentPage,err := a.GetInt("page")

	//收索查询功能，入参
	kw := a.GetString("kw")
	// 偏移量
	offsetNum := pagePerNum * (currentPage - 1)
	//打印查询信息
	ret :=fmt.Sprintf("用户查询角色信息，当前页：%d;查询条件:%s",currentPage,kw)
	logs.Info(ret)

	var count int64 = 0
	if kw != "" { //有查询条件的
		// 总记录数 ,,__contains包含列
		count, _ = qs.Filter("is_delete", 0).Filter("role_name__contains",kw).Count()
		qs.Filter("is_delete", 0).Filter("role_name__contains",kw).Limit(pagePerNum).Offset(offsetNum).All(&roles)
	}else {
		// 总记录数
		count, _ = qs.Filter("is_delete", 0).Count()
		qs.Filter("is_delete", 0).Limit(pagePerNum).Offset(offsetNum).All(&roles)
	}
	if err != nil { //说明没有获取到当前页
		currentPage = 1
	}

	//总页数
	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))

	// 上一页
	prePage := 1
	if currentPage == 1 {
		prePage = currentPage
	} else if currentPage > 1 {
		prePage = currentPage - 1
	}
	// 下一页
	nextPage := 1
	if currentPage < countPage {
		nextPage = currentPage + 1
	} else if currentPage >= countPage {
		nextPage = countPage
	}
	page_map := utils.Paginator(currentPage, pagePerNum, count)

	a.Data["page_map"] = page_map
	a.Data["currentPage"] = currentPage
	a.Data["countPage"] = countPage
	a.Data["count"] = count
	a.Data["roles"] = roles
	a.Data["prePage"] = prePage
	a.Data["nextPage"] = nextPage
	a.Data["kw"] = kw
	a.TplName = "auth/role_list.html"
}

//角色添加
func (a *RoleController) ToAdd() {
	a.TplName = "auth/role_add.html"
}

func (a *RoleController) DoAdd() {
	is_active,_ := a.GetInt("is_active")
	role_name := a.GetString("role_name")
	role_desc := a.GetString("desc")

	o := orm.NewOrm()
	role_data := auth.Role{RoleName:role_name,Desc:role_desc,IsActive:is_active,CreateTime:time.Now(),UpdatedTime:time.Now()}
	_,err := o.Insert(&role_data)
	message_map := map[string]interface{}{}
	if err != nil { //说明插入数据有问题
		ret_addinfo :=fmt.Sprintf("添加角色出错，添加信息：RoleName%s|Desc%s|" +
			"is_active%d",role_name,role_desc,is_active)
		ret :=fmt.Sprintf("添加权限出错，错误信息：%v",err)
		logs.Error(ret_addinfo)
		logs.Error(ret)
		message_map["code"] = 1001
		message_map["msg"] = "添加角色出错，请重新添加！"
		a.Data["json"] = message_map
	}else {
		ret_addinfo :=fmt.Sprintf("添加角色成功，添加信息：RoleName%s|Desc%s|" +
			"is_active%d",role_name,role_desc,is_active)
		logs.Info(ret_addinfo)
		message_map["code"] = 200
		message_map["msg"] = "添加角色成功！"
		a.Data["json"] = message_map
	}
	a.ServeJSON()

}

//批量删除
func (u *RoleController) MuliDelete() {
	ids := u.GetString("ids")
	//得到的结果"3,7,8,9",需要截取掉两边引号为 3,7,8,9
	new_ids :=ids[1:len(ids)-1]
	//，切割符号为逗号
	id_arr := strings.Split(new_ids,",")
	o := orm.NewOrm()
	qs := o.QueryTable("sys_role")
	for _, v := range id_arr{
		//字符串转int64
		id_int := utils.StrToInt(v)
		qs.Filter("sys_id",id_int).Update(orm.Params{
			"is_delete":1,
		})
	}
	ret :=fmt.Sprintf("角色删除功能，批量删除成功：用户ids:%s;",ids)
	logs.Info(ret)
	u.Data["json"] = map[string]interface{}{"code":200,"msg":"批量删除成功！"}
	u.ServeJSON()
}


// 角色--一用户配置
func (r *RoleController) ToRoleUser()  {
	role_id,_ := r.GetInt("role_id")

	o := orm.NewOrm()
	role := auth.Role{}
	o.QueryTable("sys_role").Filter("sys_id",role_id).One(&role)

	// 已绑定的用户
	o.LoadRelated(&role,"User")


	// 未绑定的用户
	users := []auth.User{}
	if len(role.User) > 0 {
		o.QueryTable("sys_user").Filter("is_delete",0).Filter("is_active",1).Exclude("sys_id__in",role.User).All(&users)

	}else {   // 没有绑定的数据
		o.QueryTable("sys_user").Filter("is_delete",0).Filter("is_active",1).All(&users)

	}

	r.Data["role"] = role
	r.Data["users"] = users
	r.TplName = "auth/role_user_add.html"

}


// 角色--一用户配置
func (r *RoleController) DoRoleUser()  {
	role_id,_ := r.GetInt("role_id")
	user_ids := r.GetString("user_ids")
    //获取的用户ID进行分片[8,9,10]
	//new_user_ids := user_ids[1:len(user_ids)-1]
	user_id_arr := strings.Split(user_ids,",")

	// "10,12,13"

	o := orm.NewOrm()
	//初始化一个值
	role := auth.Role{SysId:role_id}

	// 查询出已绑定的数据,多对多插入QueryM2M
	m2m := o.QueryM2M(&role,"User")
	m2m.Clear()

	for _,user_id := range user_id_arr{
		user := auth.User{SysId:utils.StrToInt(user_id)}
		// 通过多对多role查User，User模型名称
		m2m := o.QueryM2M(&role,"User")
		m2m.Add(user)

	}

	r.Data["json"] = map[string]interface{}{"code":200,"msg":"添加成功"}
	r.ServeJSON()
}

// 角色--权限配置
func (r *RoleController) ToRoleAuth()  {
	role_id,_ := r.GetInt("role_id")

	o := orm.NewOrm()
	qs := o.QueryTable("sys_role")
	role := auth.Role{}
	qs.Filter("sys_id",role_id).One(&role)
	r.Data["role"] = role
	r.TplName = "auth/role_auth_add.html"

}

func (r *RoleController) GetAuthJson()  {
	role_id,_ := r.GetInt("role_id")


	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth")

	// 已绑定的权限
	role := auth.Role{SysId:role_id}
	o.LoadRelated(&role,"Auth")

	//[11,14,16]
	auth_ids_has := []int{}
	for _,auth_data := range role.Auth{
		auth_ids_has = append(auth_ids_has,auth_data.SysId)
	}




	// 所有的权限
	auths := []auth.Auth{}
	qs.Filter("is_delete",0).All(&auths)

	auth_arr_map := []map[string]interface{}{}  // map数组

	for _,auth_data := range auths{
		id := auth_data.SysId
		pId := auth_data.Pid
		name := auth_data.AuthName
		if pId == 0 {
			auth_map := map[string]interface{}{"id":id,"pId":pId,"name":name,"open":false}
			auth_arr_map = append(auth_arr_map,auth_map)
		}else {
			auth_map := map[string]interface{}{"id":id,"pId":pId,"name":name}
			auth_arr_map = append(auth_arr_map,auth_map)
		}

	}

	auth_maps := map[string]interface{}{}
	auth_maps["auth_arr_map"] = auth_arr_map
	auth_maps["auth_ids_has"] = auth_ids_has
	r.Data["json"] = auth_maps
	r.ServeJSON()

}

func (r *RoleController) DoRoleAuth()  {

	role_id,_ := r.GetInt("role_id")
	auth_ids := r.GetString("auth_ids")
	//"13,15,16"       "13  15    16"
	//new_auth_ids := auth_ids[1:len(auth_ids)-1]
	id_arr := strings.Split(auth_ids,",")


	o := orm.NewOrm()
	role := auth.Role{SysId:role_id}
	m2m := o.QueryM2M(&role,"Auth")
	m2m.Clear()

	for _,auth_id := range id_arr{
		auth_id_int := utils.StrToInt(auth_id)
		if auth_id_int !=0 {
			auth_data := auth.Auth{SysId:auth_id_int}
			m2m := o.QueryM2M(&role,"Auth")
			m2m.Add(auth_data)
		}

	}

	r.Data["json"] = map[string]interface{}{"code":200,"msg":"添加成功"}
	r.ServeJSON()


}